package cn.jishiyu11.xeqb.fragment

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import cn.jishiyu11.xeqb.EntityClass.FragmengData.Mock_HomeBean
import cn.jishiyu11.xeqb.R
import cn.jishiyu11.xeqb.adapter.HomeRecyclerViewAdapter
import cn.jishiyu11.xeqb.base.BaseFragment
import cn.jishiyu11.xeqb.http.http.i.DataCallBack
import cn.jishiyu11.xeqb.http.http.i.httpbase.OkHttpManager
import cn.jishiyu11.xeqb.service.UpdataService
import cn.jishiyu11.xeqb.utils.DisplayUtils
import cn.jishiyu11.xeqb.utils.showShortToast
import cn.jishiyu11.xeqb.utils.showShortToastNetError
import cn.jishiyu11.xeqb.view.Marquee
import cn.jishiyu11.xeqb.view.PublicPhoneDialog
import com.google.gson.Gson
import com.umeng.analytics.MobclickAgent
import kotlinx.android.synthetic.main.footermore.*
import kotlinx.android.synthetic.main.frg_loancard_layout.*
import kotlinx.android.synthetic.main.tab_activity_fra.*
import okhttp3.Request
import java.io.IOException
import java.util.*


/**
 * Created by jsy_zj on 2018-03-16.
 * @param filter  网络请求返回过滤标志
 * @param urls 网络请求地址
 * @param actionBarIsShow 标题栏是否显示
 * @param bartitle 标题栏标题
 */
@SuppressLint("ValidFragment")
class BaseNewsFragment constructor(urls:String,filter:String,actionBarIsShow:Boolean,bartitle:String):BaseFragment(),DataCallBack {

    private var url:String? = null
    private var filterName:String? =null
    private var  barShow:Boolean? = false
    private var title:String? = null


    private var homerecyclerviewadapter:HomeRecyclerViewAdapter? = null
    private var homebeanList:MutableList<Mock_HomeBean.Data>? = ArrayList()
    private var hanlder: Handler? = null
    private val CHANTE_PAAGER_TIME:Long = 3000
    private var CHANGE_PAGER = 1
    private var ISPAUSE = false
    private var IS_FIRST_RESUME = true
    private var mIsRefresh = false
    private var mIsAddMore = false
    private var marquees:MutableList<Marquee>? = null
    private var page = 1


    //计算滑动距离数据
    private var scrollY:Int? = 0
    private var vpHight:Int? = 0

    init {
        this.url = urls
        filterName = filter
        barShow = actionBarIsShow
        title = bartitle
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        title_image.visibility = View.INVISIBLE
        title_complete.visibility = View.INVISIBLE
        title_view.text = title//标题

        if (barShow!!){//首页不显示，其他显示
            frg_backtitle.visibility = View.VISIBLE
            home_include_bar.visibility = View.VISIBLE
            frg_home_recyclerView.setBackgroundColor(resources.getColor(R.color.common_gray_bankitem_back))
        }
        initView()
    }


    override val layout: Int
        get() = R.layout.frg_loancard_layout

    override fun initView() {
        vpHight = DisplayUtils.dip2px(activity,200F)

        frg_home_recyclerView.layoutManager = LinearLayoutManager(activity)

        homerecyclerviewadapter = HomeRecyclerViewAdapter(activity!!,homebeanList!!,ISPAUSE)

        frg_home_recyclerView.adapter = homerecyclerviewadapter

        hanlder = homerecyclerviewadapter?.getAdapterHandler()

        frg_home_recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                var layoutManager: LinearLayoutManager = recyclerView?.layoutManager as LinearLayoutManager
                var lastPosition = layoutManager.findLastVisibleItemPosition()
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastPosition == homebeanList!!.size){
                    if (!mIsAddMore){
                        mIsAddMore = true
                        if (homebeanList?.size!=0){
                            page +=1
//                            println("page=========="+page)
                            getData()
                        }
                    }
                }

            }

            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (!barShow!!){
                    //动态设置actionbar 透明度
                    scrollY = scrollY!! + dy
                    if (vpHight!! >= scrollY!!) {
                        if (scrollY!! >= 1) {
                            home_include_bar.visibility = View.VISIBLE
                            if (scrollY!! >= vpHight!!) {
                                home_include_bar.alpha = 1.0F
                            } else if (scrollY!! > vpHight!! * 9 / 10) {
                                home_include_bar.alpha = 0.9F
                            } else if (scrollY!! > vpHight!! * 8 / 10) {
                                home_include_bar.alpha = 0.8F
                            } else if (scrollY!! > vpHight!! * 7 / 10) {
                                home_include_bar.alpha = 0.7F
                            } else if (scrollY!! > vpHight!! * 6 / 10) {
                                home_include_bar.alpha = 0.6F
                            } else if (scrollY!! > vpHight!! * 5 / 10) {
                                home_include_bar.alpha = 0.5F
                            } else if (scrollY!! > vpHight!! * 4 / 10) {
                                home_include_bar.alpha = 0.4F
                            } else if (scrollY!! > vpHight!! * 3 / 10) {
                                home_include_bar.alpha = 0.3F
                            } else if (scrollY!! > vpHight!! * 2 / 10) {
                                home_include_bar.alpha = 0.2F
                            } else if (scrollY!! > vpHight!! / 10) {
                                home_include_bar.alpha = 0.1F
                            } else {
                                home_include_bar.alpha = 0.1F
                            }
                        } else {
                            home_include_bar.visibility = View.INVISIBLE
                        }
                    }else{
                        home_include_bar.visibility = View.VISIBLE
                        home_include_bar.alpha = 1.0F
                    }

                }
            }
        })



        frg_home_refreshLayout.setOnRefreshListener {
            if (!mIsRefresh){
                mIsRefresh = true
                page = 1
                getData()
            }
        }
    }

    fun getData(){
        OkHttpManager.getAsync(url+"&page=$page",filterName!!,this)
    }


    override fun requestFailure(request: Request, name: String, e: IOException) {

        if (name.equals(filterName)){
            AddMore()
            Refresh()
            activity.showShortToastNetError()
        }
    }

    override fun requestSuccess(result: String, name: String) {

        when(name){
            filterName -> {
//                println("============"+result)
                result.trim()
                var homeBeans =  Gson().fromJson(result, Mock_HomeBean::class.java)
                if (homeBeans.code.toInt() == 200){
                    if (homebeanList?.size!=0 && mIsRefresh){
                        homebeanList?.clear()
                    }
                    Refresh()
                    homebeanList?.addAll(homeBeans?.data!!)
                    homerecyclerviewadapter?.notifyDataSetChanged()
                    if (mIsAddMore) mIsAddMore=false
                    footer_layout_text.setText(getString(R.string.load_more_pleace_wait))
                    footer_layout_loading.visibility = View.VISIBLE
                }else{
                    if (homeBeans.code.toInt() ==205){
                        AddMore()
                        Refresh()
//                        activity.showShortToast(homeBeans.msg.toString())
                    }else if (homeBeans.code.toInt() == 300){
                        AddMore()
                        Refresh()
                        activity.showShortToast("系统关闭中！")
                    }
                }


            }
        }
    }

    private fun AddMore(){
        if (mIsAddMore){
            mIsAddMore = false
            if (page>1) page -=1
            footer_layout_text.setText(getString(R.string.load_more_no_more))
            footer_layout_loading.visibility = View.GONE
        }
    }

    private fun Refresh(){
        if (mIsRefresh) {
            mIsRefresh = false
            frg_home_refreshLayout.isRefreshing = false
        }
    }

    override fun onResume() {
        super.onResume()
        ISPAUSE =false
        if (!IS_FIRST_RESUME){
            hanlder?.sendEmptyMessageDelayed(CHANGE_PAGER,CHANTE_PAAGER_TIME)
        }else{
            getData()//加载数据
        }
        MobclickAgent.onPageStart(filterName) //统计页面，"MainScreen"为页面名称，可自定义
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPageEnd(filterName)
        ISPAUSE = true
        IS_FIRST_RESUME = false
    }

    override fun onDestroy() {
        super.onDestroy()
        if (hanlder!=null){
            hanlder!!.removeMessages(CHANGE_PAGER)
            hanlder!!.removeCallbacksAndMessages(null)
        }
    }

    private fun getPhone(msg: String, phone: String) {
        val builder = PublicPhoneDialog.Builder(activity)
        builder.setTiltleMsg(msg)
        if (phone == "2") {
            builder.setTitle("建议更新")

            builder.setContentViewCancel("取消",object :DialogInterface.OnClickListener{
                override fun onClick(dialog: DialogInterface?, which: Int) {
                    //                getBOOTAPP()
                    dialog?.dismiss()
                }
            })
        } else {
            builder.setTitle("强制更新")
        }
        builder.setContentViewDetermine("确定",object :DialogInterface.OnClickListener{
            override fun onClick(dialog: DialogInterface?, which: Int) {
                var intent = Intent(context, UpdataService::class.java)
                intent.putExtra("url","http://imtt.dd.qq.com/16891/23CDD312C291655F8DA8A996BE79C59F.apk?fsname=com.jsy.jsydemo_0.0.5_5.apk&csr=1bbd");
                activity.startService(intent)
                dialog?.dismiss()
//            System.exit(0)
            }
        })
        builder.create().show()
    }



    private fun setMarqueeView(){
        marquees = ArrayList<Marquee>()
        for (i in 0 until 30){
            var marquee = Marquee()
            marquee.context  = phoneStarnum()+"****"+testRandomphoneLast()+"通过信用卡成功收款"+Random2()+"元"
            marquees?.add(marquee)
        }
        marqueeView.startWithList(marquees)
    }


    private fun Random2(): String {
        return (((Random().nextInt(9400))+ 500)+(Random().nextInt(100)/100F)).toString() + ""
    }


    //生成随机数 手机后4为随机数
    private fun testRandomphoneLast(): String {
        return (Random().nextInt(8999) + 1000).toString() + ""
    }

    /**
     * 手机号开头
     * */
    private fun phoneStarnum(): String {
        var i = 0
        i = Random().nextInt(23)
        return this.resources.getStringArray(R.array.phonestarnum)[i] + ""
    }



}